import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// create an axios instance

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // console.log(config, 'sds')
    const token = store.state.user.token
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    } else {
      console.log('没有token')
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(

  response => {
    if (response.data.success) {
      if (response.data && response.data.data && response.data.data.token) {
        Message.success('登陆成功')
      }

      return response.data
    } else {
      return Message({
        message: response.data.message,
        type: 'error'
      })
    }
  },
  error => {
    let time = null
    if (error.response && error.response.data && error.response.data.code && error.response.data.code === 10002) {
      store.commit('user/removeToken')
      router.push('/login')
      Message({
        type: 'error',
        message: 'token过期!'
      })
    }
    clearTimeout(time)
    time = 0
    console.log(time)
    time = setTimeout(() => {
      Message({
        type: 'error',
        message: '服务器开小差了'
      })
      console.log('time')
    }, 1000)
    console.log(time)

    console.log('err' + error) // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  }
)

export default service
